from os import path
from os import system
from os import makedirs
from tool import test_print
import requests

# 初始化背景
system('color 02')
download_root_path_ack = path.join('d:\\', '学诚下载', '爱课程')


# 格式化文本，防止非法字符
def format_text(text):
    return ''.join(text.strip().replace('\n', '').replace('/', '').replace('\\', '')
                   .replace(':', '').replace('*', '').replace('?', '').replace('"', '')
                   .replace('<', '').replace('>', '').replace('|', '').replace(' ', '_').split())


# 创建文件路径
def creat_file(file_path):
    is_exists = path.exists(file_path)
    if not is_exists:
        makedirs(file_path)
    else:
        test_print('[路径已存在]')


# 下载文件
def download_file(file_url, file_path, file_name):
    test_print(f'lib\\aria2c {file_url} -d {file_path} -o {file_name} -j 1 -s 16 -x 16 -k 5M -c')
    system(f'lib\\aria2c {file_url} -d {file_path} -o {file_name} -j 1 -s 16 -x 16 -k 5M -c')


# 创建下载任务
def creat_download(file_name, file_url, file_path):
    file_type = file_url[-4:]
    test_print(file_name + file_type + file_url + file_path)
    download_file(file_url, file_path, file_name + file_type)


# 下载爱课程
def download_akc(course_num):
    print('[正在搜索 ' + course_num + '...]')
    # 登陆手机App
    app_ack_login_headers = {'Content-Type': 'application/x-www-form-urlencoded',
                             'User-Agent': 'OriginalM/3.0.588.588/2.1.106/2(Xiaomi MI 6;Android 8.0.0)'}
    app_ack_login_post_data = {'userName': '18390953078', 'password': 'IHICB2459TYUK'}
    app_ack_login_result = requests.post('http://mobile.icourses.cn/hep-mobile/sword/app/login/login',
                                         headers=app_ack_login_headers, data=app_ack_login_post_data).json()
    test_print(app_ack_login_result)
    login_result = app_ack_login_result['message']
    if login_result == '操作成功':
        test_print('登陆成功')
        # 获取课程详情信息
        app_ack_chapter_headers = {'Content-Type': 'application/x-www-form-urlencoded',
                                   'User-Agent': 'OriginalM/3.0.588.588/2.1.106/2(Xiaomi MI 6;Android 8.0.0)'}
        app_ack_chapter_post_data = {'courseId': course_num}
        app_ack_chapter_result = requests.post(
            'http://mobile.icourses.cn/hep-mobile//sword/app/share/intro/getIntroduction',
            headers=app_ack_chapter_headers, data=app_ack_chapter_post_data).json()
        test_print(app_ack_chapter_result)
        chapter_result = app_ack_chapter_result['message']
        if chapter_result == '操作成功':
            test_print('获取章节信息成功')
            # 名称
            course_text = format_text(app_ack_chapter_result['data']['base']['title'])
            print('大学：' + course_text)
            # 大学
            course_university = format_text(app_ack_chapter_result['data']['school']['schoolName'])
            print('来源：' + course_university)
            # 学时
            course_hour = format_text(app_ack_chapter_result['data']['base']['studyTime'].split('.')[0])
            print('学时：' + course_hour)
            # 主讲人
            course_teacher = format_text(app_ack_chapter_result['data']['mainTeacher'][0]['realname'])
            print('主讲：' + course_teacher + '\n')
            # 创建课程文件夹
            course_path = path.join(download_root_path_ack,
                                    course_num + '_' + course_text + '_视频教程' + '_' + course_university + '_' + course_teacher + '_' + course_hour + '学时' + '_有课件')
            creat_file(course_path)
            # 教材目录及参考教材
            with open(path.join(course_path, '目录及教材.txt'), 'w', encoding='utf-8') as file:
                if len(app_ack_chapter_result['data']['mainMaterial']) > 0:
                    main_book_result = app_ack_chapter_result['data']['mainMaterial'][0]
                    main_book_tip = format_text(main_book_result['materialTypeDesc'])
                    main_book_title = format_text(main_book_result['materialName'])
                    main_book_isbn = format_text(main_book_result['iSBN'])
                    main_book_author = format_text(main_book_result['materialAuthor'])
                    main_book_publisher = format_text(main_book_result['materialPublisher'])
                    file.write('        参考教材：\n')
                    file.write(main_book_tip + '\n')
                    file.write(main_book_title + '\n')
                    file.write('ISBN:' + main_book_isbn + '\n')
                    file.write('主编:' + main_book_author + '\n')
                    file.write(main_book_publisher + '\n')
                if len(app_ack_chapter_result['data']['asistMaterial']) > 0:
                    for sub_book in app_ack_chapter_result['data']['asistMaterial']:
                        sub_book_tip = format_text(sub_book['materialTypeDesc'])
                        sub_book_title = format_text(sub_book['materialName'])
                        sub_book_isbn = format_text(sub_book['iSBN'])
                        sub_book_author = format_text(sub_book['materialAuthor'])
                        sub_book_publisher = format_text(sub_book['materialPublisher'])
                        file.write('\n' + sub_book_tip + '\n')
                        file.write(sub_book_title + '\n')
                        file.write('ISBN:' + sub_book_isbn + '\n')
                        file.write('主编:' + sub_book_author + '\n')
                        file.write(sub_book_publisher + '\n')
                file.write('\n\n\n        课程目录：\n')
                main_result = app_ack_chapter_result['data']['characters']
                for main_index in range(len(main_result)):
                    main_chapter_title = format_text(main_result[main_index]['title'])
                    file.write('第' + str(main_index + 1) + '章 ' + main_chapter_title + '\n')
                    sub_result = main_result[main_index]['childList']
                    if len(sub_result) > 0:
                        for sub_index in range(len(sub_result)):
                            sub_chapter_title = format_text(sub_result[sub_index]['title'])
                            file.write('第' + str(sub_index + 1) + '节 ' + sub_chapter_title + '\n')
            # 获取章节资源
            app_ack_resource_headers = {'Content-Type': 'application/x-www-form-urlencoded',
                                        'User-Agent': 'OriginalM/3.0.588.588/2.1.106/2(Xiaomi MI 6;Android 8.0.0)'}
            app_ack_resource_post_data = {'courseId': course_num}
            app_ack_resource_result = requests.post(
                'http://mobile.icourses.cn/hep-mobile/sword/app/share/detail/getCharacters',
                headers=app_ack_resource_headers, data=app_ack_resource_post_data).json()
            test_print(app_ack_resource_result)
            resource_result = app_ack_resource_result['message']
            if resource_result == '操作成功':
                test_print('获取章节资源成功')
                resource_list = app_ack_resource_result['data']
                for main_index in range(len(resource_list)):
                    main_chapter_title = format_text(resource_list[main_index]['title'])
                    # 创建主章节文件夹
                    main_chapter_path = path.join(course_path,
                                                  '第' + str(main_index + 1) + '章_' + main_chapter_title)
                    creat_file(main_chapter_path)
                    # 创建下载任务
                    main_resource_result = resource_list[main_index]['resList']
                    if len(main_resource_result) > 0:
                        for main_resource_index in range(len(main_resource_result)):
                            main_resource_title = format_text(main_resource_result[main_resource_index]['title'])
                            main_resource_url = main_resource_result[main_resource_index]['fullResUrl']
                            creat_download(main_resource_title, main_resource_url, main_chapter_path)
                    sub_chapter_result = resource_list[main_index]['childList']
                    if len(sub_chapter_result) > 0:
                        for sub_index in range(len(sub_chapter_result)):
                            # 创建子章节文件夹
                            sub_chapter_title = format_text(sub_chapter_result[sub_index]['title'])
                            sub_chapter_path = path.join(course_path,
                                                         '第' + str(main_index + 1) + '章_' + main_chapter_title,
                                                         '第' + str(sub_index + 1) + '节_' + sub_chapter_title)
                            creat_file(sub_chapter_path)
                            sub_resource_result = sub_chapter_result[sub_index]['resList']
                            for sub_resource_index in range(len(sub_resource_result)):
                                sub_resource_title = format_text(sub_resource_result[sub_resource_index]['title'])
                                sub_resource_url = sub_resource_result[sub_resource_index]['fullResUrl']
                                if sub_resource_url is None:
                                    pass
                                else:
                                    creat_download(sub_resource_title, sub_resource_url, sub_chapter_path)
            elif resource_result == '操作失败，后台异常':
                print('获取章节资源失败[可能原因：无此章节]')
            else:
                print('获取章节资源失败[可能原因：未知]')
        elif chapter_result == '操作失败，后台异常':
            print('获取章节信息失败[可能原因：无此课程]')
        else:
            print('获取章节信息失败[可能原因：未知]')
    elif login_result == '用户名密码验证失败':
        print('用户名密码验证失败')
    else:
        print('登陆错误')


if __name__ == '__main__':
    pass
